import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

// Custom plugin to handle Chart.js version property redefinition
const chartJsVersionPlugin = () => {
  return {
    name: 'chartjs-version-plugin',
    transform(code, id) {
      // Target Chart.js version definition file
      if (id.includes('node_modules/chart.js') && code.includes('defineProperty(exports, "version"')) {
        // Wrap the version definition in a conditional to avoid re-definition
        const modifiedCode = code.replace(
          /Object\.defineProperty\(exports,\s*["']version["']/g,
          'if(!Object.getOwnPropertyDescriptor(exports, "version")) Object.defineProperty(exports, "version"'
        );
        return {
          code: modifiedCode,
          map: null
        };
      }
      return null;
    }
  };
};

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react({
      // 使用标准JSX运行时
      jsxRuntime: 'automatic',
      // 开发模式下使用刷新
      fastRefresh: true
    }),
    chartJsVersionPlugin()
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  optimizeDeps: {
    include: ['chart.js']
  },
  build: {
    commonjsOptions: {
      include: [/chart\.js/, /node_modules\//],
      defaultIsModuleExports: true
    },
    rollupOptions: {
      // 配置外部依赖,这些库不会被打包
      external: [],
      output: {
        // 在UMD构建模式下为外部依赖提供全局变量
        globals: {
          'react': 'React',
          'react-dom': 'ReactDOM',
          'react-dom/client': 'ReactDOMClient'
        }
      }
    }
  },
  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://43.138.154.168:8000/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})
